
/*! License Center Flow - Ruotong Music (client-only) */
(function(){
  'use strict';
  const $ = (s, c=document) => c.querySelector(s);
  const $$ = (s, c=document) => Array.from(c.querySelectorAll(s));
  const fmt = (d) => new Date(d).toLocaleString();
  const storage = {
    get(k, fb){ try{ return JSON.parse(localStorage.getItem(k) || JSON.stringify(fb)); }catch(e){ return fb; } },
    set(k, v){ localStorage.setItem(k, JSON.stringify(v)); }
  };
  const COMPANY = {
    name: "北京嘉道文华文化有限公司",
    brand: "Ruotong Music",
    contact: "support@ruotongmusic.com"
  };
  const STATE = {
    tracks: [],
    filter: 'all', // all | authorized | unauthorized
    q: '',
    licenses: {}, // { [trackId]: License }
  };

  function uid(len=5){
    const seg = () => Math.random().toString(36).slice(2, 2+len);
    return `${seg()}-${seg()}-${seg()}-${seg()}-${seg()}`;
  }

  async function loadTracks(){
    try{
      const r = await fetch('assets/data/tracks.json');
      if(!r.ok) throw new Error('tracks json not found');
      STATE.tracks = await r.json();
    }catch(e){
      // fallback to inline demo
      STATE.tracks = [
        { id: 'demo-1', title: 'Demo Track 1', artist: 'Artist', audioUrl: '#', cover: '', purpose:'个人用途（非商用）', scope:'个人账户', region:'中国', term:'随片永久', subscriptionEligible:true },
      ];
    }
  }

  function loadLicenses(){
    STATE.licenses = storage.get('rt.licenses', {});
  }
  function saveLicenses(){
    storage.set('rt.licenses', STATE.licenses);
  }

  function isAuthorized(track){ return !!STATE.licenses[track.id]; }

  function render(){
    const root = $('#rt-license-root');
    if(!root) return;
    const list = root.querySelector('.rtacc-list');
    const q = (STATE.q || '').trim().toLowerCase();

    const tracks = STATE.tracks.filter(t => {
      if(STATE.filter==='authorized' && !isAuthorized(t)) return false;
      if(STATE.filter==='unauthorized' && isAuthorized(t)) return false;
      if(q){
        const lic = STATE.licenses[t.id];
        const code = lic?.code || '';
        const hay = `${t.title} ${t.artist} ${code}`.toLowerCase();
        return hay.includes(q);
      }
      return true;
    });

    list.innerHTML = tracks.map(t => renderItemHTML(t)).join('') || `<div class="rtacc-empty">暂无数据</div>`;

    // Attach events for newly rendered items
    list.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', onListAction);
    });
  }

  function renderItemHTML(t){
    const lic = STATE.licenses[t.id];
    const activeBadge = lic ? `<span class="rtacc-badge success">已激活</span>` : `<span class="rtacc-badge">未激活</span>`;
    const purpose = t.purpose || '—';
    const scope = t.scope || '—';
    const region = t.region || '—';
    const term = t.term || '—';
    const cover = t.cover ? `<img src="${t.cover}" alt="" />` : '';
    const btnView = lic ? `<button class="rtacc-btn" data-action="view" data-id="${t.id}">查看授权书</button>` : `<button class="rtacc-btn" data-action="view" data-id="${t.id}" disabled>查看授权书</button>`;
    const btnGen = lic ? `<button class="rtacc-btn" data-action="regen" data-id="${t.id}">重新生成</button>` : `<button class="rtacc-btn primary" data-action="generate" data-id="${t.id}">生成授权书</button>`;
    const downloadBtn = t.audioUrl && t.audioUrl !== '#' ? `<a class="rtacc-btn" href="${t.audioUrl}" download>下载音乐</a>` : `<button class="rtacc-btn" disabled>下载音乐</button>`;

    return `
      <div class="rtacc-item" data-id="${t.id}">
        <div class="rtacc-cover">${cover}</div>
        <div class="rtacc-meta">
          <div class="rtacc-title">${t.title} ${activeBadge}</div>
          <div class="rtacc-muted">by ${t.artist || '未知'}</div>
          <div class="rtacc-kv">
            <div><span>授权用途：</span>${purpose}</div>
            <div><span>授权范围：</span>${scope}</div>
            <div><span>授权地域：</span>${region}</div>
            <div><span>授权期限：</span>${term}</div>
          </div>
        </div>
        <div class="rtacc-actions">
          ${downloadBtn}
          ${btnView}
          ${btnGen}
        </div>
      </div>
    `;
  }

  function onListAction(e){
    const btn = e.currentTarget;
    const id = btn.dataset.id;
    const track = STATE.tracks.find(t=>t.id===id);
    if(!track) return;

    switch(btn.dataset.action){
      case 'view': openLicense(track); break;
      case 'generate': openWizard(track); break;
      case 'regen': openWizard(track, STATE.licenses[id]); break;
    }
  }

  function bind(){
    const root = $('#rt-license-root');
    if(!root) return;
    // Filters
    const [btnAll, btnA, btnU] = $$('.rtacc-filter-btn', root);
    const setActive = (btn) => { $$('.rtacc-filter-btn', root).forEach(b=>b.classList.remove('active')); btn.classList.add('active'); };
    btnAll?.addEventListener('click', ()=>{ setActive(btnAll); STATE.filter='all'; render(); });
    btnA?.addEventListener('click', ()=>{ setActive(btnA); STATE.filter='authorized'; render(); });
    btnU?.addEventListener('click', ()=>{ setActive(btnU); STATE.filter='unauthorized'; render(); });

    // Search
    $('.rtacc-search input', root)?.addEventListener('input', (e)=>{ STATE.q = e.target.value; render(); });

    // Wizard form submit (Generate license)
    $('#wizard-form')?.addEventListener('submit', (e)=>{
      e.preventDefault();
      const data = readWizardForm();
      const trackId = $('#wiz-track-id').value;
      const track = STATE.tracks.find(t=>t.id===trackId);
      if(!track) return;
      const license = buildLicense(track, data);
      STATE.licenses[track.id] = license;
      saveLicenses();
      closeDialog('#license-wizard-dialog');
      render();
      openLicense(track);
    });

    // License dialog buttons
    $('#license-download')?.addEventListener('click', downloadLicenseCurrent);
    $('#license-print')?.addEventListener('click', ()=>printDialog('#license-view-dialog'));
    $$('#license-view-dialog [data-close]').forEach(btn=>btn.addEventListener('click', ()=>closeDialog('#license-view-dialog')));
    $$('#license-wizard-dialog [data-close]').forEach(btn=>btn.addEventListener('click', ()=>closeDialog('#license-wizard-dialog')));
  }

  function openWizard(track, existing=null){
    $('#wiz-track-title').textContent = track.title;
    $('#wiz-track-id').value = track.id;
    // Reset fields
    $('#wiz-project').value = existing?.project || '';
    $('#wiz-owner').value = existing?.grantee || '';
    // usage plan
    const subInput = $('#wiz-plan-sub'); const singleInput = $('#wiz-plan-single');
    subInput.disabled = !track.subscriptionEligible;
    if(track.subscriptionEligible){ subInput.checked = true; } else { singleInput.checked = true; }
    // channels
    $$('#wiz-channels input[type="checkbox"]').forEach(cb => { cb.checked = existing?.channels?.includes(cb.value) || false; });
    // misc
    $('#wiz-purpose').value = existing?.purpose || (track.purpose || '个人用途（非商用）');
    $('#wiz-scope').value = existing?.scope || (track.scope || '个人账户');
    $('#wiz-region').value = existing?.region || (track.region || '中国');
    $('#wiz-term').value = existing?.term || (track.term || '随片永久');
    openDialog('#license-wizard-dialog');
  }

  function readWizardForm(){
    const plan = $('input[name="wiz-plan"]:checked')?.value || 'single';
    const channels = $$('#wiz-channels input[type="checkbox"]:checked').map(cb=>cb.value);
    return {
      plan,
      project: $('#wiz-project').value.trim(),
      grantee: $('#wiz-owner').value.trim(),
      purpose: $('#wiz-purpose').value,
      scope: $('#wiz-scope').value,
      region: $('#wiz-region').value,
      term: $('#wiz-term').value,
      channels
    };
  }

  function buildLicense(track, form){
    const now = new Date();
    const code = uid();
    const lic = {
      code,
      company: COMPANY.name,
      brand: COMPANY.brand,
      contact: COMPANY.contact,
      grant: '使用',
      purpose: form.purpose,
      scope: form.scope,
      region: form.region,
      term: form.term,
      musician: track.artist,
      title: track.title,
      workUrl: 'track.html', // placeholder
      project: form.project || '—',
      grantee: form.grantee || '—',
      channels: form.channels || [],
      plan: form.plan, // 'subscription' or 'single'
      activateTime: now.toISOString(),
      licenseDate: now.toISOString(),
      trackId: track.id
    };
    return lic;
  }

  function openLicense(track){
    const lic = STATE.licenses[track.id];
    if(!lic){ alert('该歌曲尚未生成授权书'); return; }
    renderLicense(lic);
    openDialog('#license-view-dialog');
  }

  function renderLicense(lic){
    const box = $('#license-view-dialog .license-preview');
    if(!box) return;
    box.innerHTML = `
      <div class="brand">Ruotong Music</div>
      <h2 style="margin: 8px 0 12px">音乐授权书</h2>
      <p class="muted">北京嘉道文华文化有限公司对非独家授权我们所有音频版权，并准许对该授权书授权证书所许可使用者使用音乐作品，适用于制作传播使用。请妥善保存授权书截图/打印件。</p>
      <div class="grid two">
        <div class="kv"><div class="k">授权项目：</div><div class="v">使用</div></div>
        <div class="kv"><div class="k">授权范围：</div><div class="v">${escapeHTML(lic.scope)}</div></div>
        <div class="kv"><div class="k">授权用途：</div><div class="v">${escapeHTML(lic.purpose)}</div></div>
        <div class="kv"><div class="k">授权地域：</div><div class="v">${escapeHTML(lic.region)}</div></div>
        <div class="kv"><div class="k">授权期限：</div><div class="v">${escapeHTML(lic.term)}</div></div>
        <div class="kv"><div class="k">音乐人：</div><div class="v">${escapeHTML(lic.musician)}</div></div>
        <div class="kv"><div class="k">作品名称：</div><div class="v">${escapeHTML(lic.title)}</div></div>
        <div class="kv"><div class="k">作品授权码：</div><div class="v">${lic.code}</div></div>
        <div class="kv"><div class="k">作品地址：</div><div class="v">(站内作品详情链接)</div></div>
        <div class="kv"><div class="k">被授权者：</div><div class="v">${escapeHTML(lic.grantee)}</div></div>
        <div class="kv"><div class="k">项目名称：</div><div class="v">${escapeHTML(lic.project)}</div></div>
        <div class="kv"><div class="k">投放渠道：</div><div class="v">${(lic.channels && lic.channels.length ? lic.channels.join('、') : '—')}</div></div>
        <div class="kv"><div class="k">激活时间：</div><div class="v">${fmt(lic.activateTime)}</div></div>
      </div>
      <div class="foot">
        <div>授权日期：${lic.licenseDate.slice(0,10)}</div>
        <div>授权单位：${escapeHTML(lic.company)}</div>
      </div>
    `;
    // keep current license in dataset for download/print
    $('#license-view-dialog').dataset.license = JSON.stringify(lic);
  }

  function downloadLicenseCurrent(){
    const dlg = $('#license-view-dialog');
    const lic = JSON.parse(dlg.dataset.license || '{}');
    if(!lic.code){ return; }
    const html = buildLicenseHTML(lic);
    const blob = new Blob([html], {type: 'text/html;charset=utf-8'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `license-${lic.code}.html`;
    document.body.appendChild(a);
    a.click();
    setTimeout(()=>{ URL.revokeObjectURL(a.href); a.remove(); }, 100);
  }

  function buildLicenseHTML(lic){
    return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"/>
      <title>${lic.brand||'Ruotong Music'} - 授权书 ${lic.code}</title>
      <style>
      body{font-family: system-ui, -apple-system, Segoe UI, Roboto, PingFang SC, Microsoft Yahei, Helvetica, Arial; background:#f5f5f5; padding:24px}
      .license{max-width:900px;margin:0 auto;background:#fff;border:1px solid #eee;border-radius:12px;padding:24px 24px 32px}
      .license h1{margin:0 0 8px}
      .grid{display:grid;grid-template-columns:1fr 1fr;gap:8px 24px;margin:16px 0}
      .kv{display:flex;gap:6px}
      .k{width:100px;color:#666}
      .v{flex:1}
      .foot{display:flex;justify-content:space-between;margin-top:16px;padding-top:8px;border-top:1px dashed #ccc}
      @media print {.license{border:none} }
      </style>
      <body onload="setTimeout(()=>window.print(), 300)">
      <div class="license">
        <h1>${lic.brand||'Ruotong Music'} 音乐授权书</h1>
        <p style="color:#666">北京嘉道文华文化有限公司对非独家授权我们所有音频版权，并准许对该授权书授权证书所许可使用者使用音乐作品，适用于制作传播使用。请妥善保存授权书。</p>
        <div class="grid">
          <div class="kv"><div class="k">授权项目：</div><div class="v">使用</div></div>
          <div class="kv"><div class="k">授权用途：</div><div class="v">${esc(lic.purpose)}</div></div>
          <div class="kv"><div class="k">授权范围：</div><div class="v">${esc(lic.scope)}</div></div>
          <div class="kv"><div class="k">授权地域：</div><div class="v">${esc(lic.region)}</div></div>
          <div class="kv"><div class="k">授权期限：</div><div class="v">${esc(lic.term)}</div></div>
          <div class="kv"><div class="k">音乐人：</div><div class="v">${esc(lic.musician)}</div></div>
          <div class="kv"><div class="k">作品名称：</div><div class="v">${esc(lic.title)}</div></div>
          <div class="kv"><div class="k">作品授权码：</div><div class="v">${lic.code}</div></div>
          <div class="kv"><div class="k">作品地址：</div><div class="v">(站内作品详情链接)</div></div>
          <div class="kv"><div class="k">被授权者：</div><div class="v">${esc(lic.grantee)}</div></div>
          <div class="kv"><div class="k">项目名称：</div><div class="v">${esc(lic.project)}</div></div>
          <div class="kv"><div class="k">投放渠道：</div><div class="v">${(lic.channels||[]).join('、') || '—'}</div></div>
          <div class="kv"><div class="k">激活时间：</div><div class="v">${new Date(lic.activateTime).toLocaleString()}</div></div>
        </div>
        <div class="foot">
          <div>授权日期：${lic.licenseDate.slice(0,10)}</div>
          <div>授权单位：${esc(lic.company)}</div>
        </div>
      </div>
      <script>function esc(s){return (s||'').replace(/[&<>]/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]))}</script>
      </body></html>`;
  }

  function escapeHTML(s){ return (s||'').replace(/[&<>]/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c])); }

  // Dialog helpers using <dialog>
  function openDialog(sel){ const d=$(sel); if(d?.showModal){ d.showModal(); }else{ d?.classList.add('open'); } }
  function closeDialog(sel){ const d=$(sel); if(d?.close){ try{ d.close(); }catch(e){ d.classList.remove('open'); } } else { d?.classList.remove('open'); } }
  function printDialog(sel){
    const d=$(sel); if(!d) return;
    const html = d.querySelector('.license-preview')?.innerHTML || '';
    const win = window.open('', '_blank');
    win.document.write(`<!doctype html><meta charset="utf-8"><title>打印授权书</title><style>
      body{font-family: system-ui, -apple-system, Segoe UI, Roboto, PingFang SC, Microsoft Yahei; padding:24px}
      .license-preview{max-width:960px;margin:0 auto}
      .grid.two{display:grid;grid-template-columns:1fr 1fr;gap:8px 24px}
      .kv{display:flex;gap:6px}.k{width:100px;color:#666}.v{flex:1}
    </style><body class="printable"><div class="license-preview">${html}</div></body>`);
    win.document.close();
    setTimeout(()=>win.print(), 300);
  }

  // Init
  (async function(){
    await loadTracks();
    loadLicenses();
    bind();
    render();
  })();
})();
